package cn.yusei.teamTribe.service.team;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.constant.RoleType;
import cn.yusei.teamTribe.dao.team.TeamDAO;
import cn.yusei.teamTribe.dao.team.TeamRoleDAO;
import cn.yusei.teamTribe.dao.team.po.TeamPO;
import cn.yusei.teamTribe.dao.team.po.TeamRolePO;
import cn.yusei.teamTribe.dao.user.UserDAO;
import cn.yusei.teamTribe.entity.Team;

@Service
public class TeamService {

	@Autowired
	private TeamDAO teamDAO;
	@Autowired
	private TeamRoleDAO teamRoleDAO;
	@Autowired
	private UserDAO userDAO;
	
	public int add(int masterId, Team team){
		TeamPO teamPO = new TeamPO();
		BeanUtils.copyProperties(team, teamPO);
		if(teamDAO.exists(teamPO)) {
			return ResponseCode.TEAM_NAME_ALREADY_EXISTS;
		}
		if(userDAO.selectById(masterId) == null)
			return ResponseCode.USER_NOT_EXISTS;
		teamDAO.insert(teamPO);	
		int teamId = teamDAO.selectLastInsertId();
		TeamRolePO teamRolePO = new TeamRolePO();
		teamRolePO.setUserId(masterId);
		teamRolePO.setTeamId(teamId);
		teamRolePO.setRoleId(RoleType.TEAM_MASTER);
		teamRoleDAO.insert(teamRolePO);
		return ResponseCode.REQUEST_SUCCESSED;
		
	}
	
	public Set<Integer> get(int schoolId, int tagId)
	{
		Set<Integer> ids = new HashSet<Integer>();
		Set<Integer> same = new HashSet<Integer>();
		if(schoolId != 0)
		{
			for(int id : getBySchool(schoolId))
				ids.add(id);
			if(tagId == 0)
				return ids;
		}
		if(tagId != 0)
		{
			for(int id : getByTag(tagId))
				if(!ids.add(id))
					same.add(id);
			if(schoolId == 0)
				return ids;
		}
		return same;
	}
	
	private int[] getBySchool(int schoolId)
	{
		int[] ids = null;
		ids = teamDAO.selectBySchool(schoolId);
		return ids;
	}
	
	private int[] getByTag(int tagId)
	{
		int[] ids = null;
		ids = teamDAO.selectByTag(tagId);
		return ids;
	}
	
}
